package com.itheima.itheima_health.controller.admin.CommonController;


import com.itheima.itheima_health.constant.MessageConstant;
import com.itheima.itheima_health.constant.RedisConstant;
import com.itheima.itheima_health.entity.Result;
import com.itheima.itheima_health.utils.QiniuUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
@Slf4j
@Api(tags = "文件上传相关接口")
public class CommonController {
    @Autowired
    private QiniuUtils qiniuUtils;
    @Autowired
    private RedisTemplate redisTemplate;
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result upload(@RequestBody MultipartFile imgFile) throws IOException {
        try {
            log.info("文件上传:{}",imgFile);

            //原始文件名
            String originalFilename = imgFile.getOriginalFilename();
            //截取原始文件名的后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新的文件名称
            String fileName = UUID.randomUUID().toString()+extension;

            log.info("图片二进制数:{}",imgFile.getBytes());

            log.info("文件名:{}",originalFilename);

            qiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);

            // 将文件名添加到 Redis 的 Set 集合中
            redisTemplate.opsForSet().add(RedisConstant.SETMEAL_PIC_RESOURCES, fileName);

            return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS,fileName);
        }catch (Exception e){
            return new Result(true, MessageConstant.PIC_UPLOAD_FAIL);
        }
    }
}
